import mongoose from 'mongoose'
import * as R from 'ramda'

const User = mongoose.model('User')
const ObjectId = mongoose.Types.ObjectId

const userSelect = {
  nickname: 1,
  email: 1,
  avatar: 1,
  _id: 1,
  age: 1,
  sex: 1,
  onLine: 1
}

// 单向添加好友
export async function addFriend(id, id2) {
  const friend = await User.findOne({
    _id: ObjectId(id2)
  })
  if (friend) {
    await User.updateOne({
      _id: ObjectId(id)
    }, {
      $addToSet: {
        friends: ObjectId(id2)
      }
    })
  }
}

// 单向删除好友
export async function delFriend(id, id2) {
  await User.updateOne({
    _id: ObjectId(id)
  }, {
    $pull: {
      friends: { $in: [ObjectId(id2)] }
    }
  })
}

// 查找所有好友
export async function getFriends(id) {
  return await User.findOne({
    _id: ObjectId(id)
  }).populate({
    path: 'friends',
    select: {
      ...userSelect
    },
    options: {
      limit: 200
    }
  })
}

// 根据昵称查找用户
export async function getUsersByKeywords(id, keywords) {
  const user = await User.findOne({
    _id: ObjectId(id)
  })

  return await User.aggregate([{
    $match: {
      nickname: {
        $regex: new RegExp(keywords, 'ig')
      },
      _id: {
        $ne: ObjectId(id)
      }
    }
  }, {
    $project: {
      ...userSelect,
      isFriend: {
        $in: ['$_id', user.friends]
      }
    }
  }]).limit(50)
}

export async function getUserById(id, me) {
  const meInfo = await User.findOne({
    _id: ObjectId(me)
  })
  let user = await User.findOne({
    _id: ObjectId(id)
  }).select({
    ...userSelect
  })
  if (user) {
    user = user.toJSON()
    user.isFriend = R.includes(String(user._id))(meInfo.friends.map(item => String(item)))
    return user
  } else {
    return null
  }
}

// 修改昵称
export async function updateNickname(id, nickname) {
  return await User.findOneAndUpdate({
    _id: ObjectId(id)
  }, {
    $set: {
      nickname
    }
  }, {new: true}).select({
    ...userSelect,
    username: 1
  })
}

// 修改性别
export async function updateSex(id, sex) {
  return await User.findOneAndUpdate({
    _id: ObjectId(id)
  }, {
    $set: {
      sex: Number(sex) === 1 ? 1 : 0
    }
  }, {new: true}).select({
    ...userSelect,
    username: 1
  })
}

// 修改年龄
export async function updateAge(id, age) {
  return await User.findOneAndUpdate({
    _id: ObjectId(id)
  }, {
    $set: {
      age
    }
  }, {new: true}).select({
    ...userSelect,
    username: 1
  })
}

// 修改邮箱
export async function updateEmail(id, email) {
  return await User.findOneAndUpdate({
    _id: ObjectId(id)
  }, {
    $set: {
      email
    }
  }, {new: true}).select({
    ...userSelect,
    username: 1
  })
}

